package com.xxxx.seckill.config;

import com.xxxx.seckill.exception.GlobalException;
import com.xxxx.seckill.exception.MobileException;
import com.xxxx.seckill.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class SeckillInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取网址
        String uri = request.getRequestURI();
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if (accessLimit == null) {
                return true;
            }
            int maxcount = accessLimit.maxCount();
            int seconds = accessLimit.seconds();
            boolean needLogin = accessLimit.needLogin();
            if (needLogin) {
                User user = UserArgumentResolver.userLocal.get();
                if (user == null) {
                    throw new MobileException("用户未登录");
                }
                ValueOperations valueOperations = redisTemplate.opsForValue();
                String count = (String) valueOperations.get("uri:" + user.getId());
                int count1 = Integer.parseInt(count);
                if (StringUtils.isEmpty(count)) {
                    valueOperations.set("uri:" + user.getId(), 1, seconds, TimeUnit.SECONDS);
                } else if (count1 <= maxcount) {
                    valueOperations.increment("uri:"+user.getId());
                }else {
                    log.info("访问过于频繁");
                    throw new MobileException("访问过于频繁");
                }
            }
        }
        return true;
    }

}
